import * as React from 'react';
import { getAssistant, getAutoComplete, searchSelectedText } from '../../services/assistant'
import { withRouter } from 'react-router-dom';
import InfoBox from './templates/InfoBox'
import Stat from './templates/Stat'
import Relation from './templates/Relation'
import './styles.less';
import DetailList from './templates/DetailList';
import News from './templates/News';
import Condition from './templates/Condition';
import Literal from './templates/Literal';
import Tag from '../../components/tag'
import SearchAutoComplete from './SearchAutoComplete';
import debounce from '../../utils/debounce';
import * as queryString from 'query-string';
import { ListContainer, ParagraphCard } from '../../components';
import classnames from 'classnames';
import Toast, { IToastState } from '../../components/Toast';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react';
import DocumentResult from './document';
import { SearchType } from '../../utils/enum';

export interface AssistantProps {
  searchType: SearchType
  keyword?: string
}

export interface AssistantState {
  showDocument?: boolean,
  showList?: boolean,
  skill: string,
  keyword: string
  list: any[],
  isCapture: boolean,
  isReadingAssistON?: boolean,
  dropDownList: any[]
  recommodList: any[]
  document?: any
}

class Assistant extends React.Component<AssistantProps, AssistantState> {
  getAutoCompleteDebounce
  constructor(props, context) {
    super(props, context);
    const { search: query = {} } = props.location
    const { search = '' } = queryString.parse(query)
    this.state = {
      showList: false,
      isCapture: false,
      isReadingAssistON: false,
      skill: '',
      keyword: search,
      list: [],
      dropDownList: [],
      recommodList: []
    };
  }

  componentDidMount() {
    this.getAutoCompleteDebounce = debounce(this.getAutoComplete, 300)
    if (this.state.keyword) {
      this.onSearch(this.state.keyword)
    }
  }

  componentWillReceiveProps(props) {
    if (props.keyword !== this.props.keyword) {
      if (props.searchType === SearchType.Text) {
        this.handleTextSearch(props.keyword)
      } else if (props.searchType === SearchType.Instance) {
        this.onSearch(props.keyword)
      }
    }
  }

  // 调用实例搜索接口
  onSearch = async value => {
    const result = await getAssistant(value)
    this.setState({
      showList: true,
      showDocument: false,
      keyword: value,
      skill: result.skill,
      list: result.data,
      recommodList: result.relatedQuestions
    })
  }

  // 改变搜索下拉
  onSearchChange = (value, toSearch?: boolean) => {
    this.setState({
      keyword: value
    })
    this.getAutoCompleteDebounce(value)
  }

  getAutoComplete = async (value) => {
    const result = await getAutoComplete(value)
    console.info('下拉', result.data)
    this.setState({
      dropDownList: result.data
    })
  }

  renderTemplate = (key, index, data, type?: string) => {
    let dom = null
    switch (key) {
      // 知识卡片
      case 'infobox':
        dom = <InfoBox key={index} res={data} />
        break;
      // 统计图
      case 'stat':
        dom = <Stat key={index} res={data} search={this.state.keyword} viewIndex={index} />
        break;
      // 关系图
      case 'relation':
      case 'graph':
      case 'path':
      case 'timing':
        dom = <Relation search={this.state.keyword} viewIndex={index} key={index} res={data} keyword={key} />
        break;
      // 实体属性和列表
      case 'kb':
        if (type === 'literal') {
          dom = <Literal key={index} res={data} />
        } else if (type === 'detail-list') {
          dom = <DetailList key={index} res={data} search={this.state.keyword} viewIndex={index} />
        } else if (type === 'object-list') {
          dom = <Condition key={index} res={data} />
        }
        break;
      // 新闻
      case 'semanticsearch':
        dom = <News key={index} res={data} />
        break;
      default:
        break;
    }
    return dom;
  }

  render() {
    const { showList, showDocument, skill, list = [], dropDownList, recommodList = [], keyword, document } = this.state

    return (
      <div className='container assistant-page'>
        <div className="top-wrap">
          <SearchAutoComplete
            placeholder="搜索知识助手内容"
            value={keyword}
            onSearch={newValue => this.onSearch(newValue)}
            onChange={value => this.onSearchChange(value)}
            options={dropDownList}
          >
          </SearchAutoComplete>

          {
            showList && (
              <ListContainer
                className="content-container"
                hideResultCount
                hidePagination
                showContent={list.length > 0}
              >
                {list.map((item, index) => {
                  const { type } = item.content
                  return this.renderTemplate(skill, index, item, type)
                })}
              </ListContainer>
            )
          }
          {recommodList && recommodList.length > 0 && <div className="recommod">
            <div className="recomend-wrapper">
              {/* <i className="ms-Icon ms-Icon--Unknown" aria-hidden="true"></i> */}
              <img className="icon" src="/assets/logo.png" width="16" alt="logo" />
              <span className="recomend">为您推荐&nbsp;&nbsp;</span>
              <span>
                {recommodList.map((item, index) => {
                  return <Tag title={item.que} onClick={() => this.onSearch(item.que)} key={index} />
                })}
              </span>
            </div>
          </div>}

          {/* TODO 区分普通搜索跟 实例搜索 划词搜索的时候才显示相关文档 */}
          {
            showDocument && <DocumentResult onChange={this.handleTextSearch} document={document} />
          }

        </div>

        {(list.length === 0 || list.length === 0) && <div className="ask-container">
          <div className="line-wrap">
            <div className="ask-title">你可以问这些</div>
            <div className="line"></div>
          </div>
          <div className="ms-Grid" dir="ltr">
            <div className="ms-Grid-row">
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--Org icon" aria-hidden="true"></i>
                <div className="title">关联分析</div>
                <div className="content">"ofo和滴滴的关系"</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--FeedbackRequestSolid icon" aria-hidden="true"></i>
                <div className="title">条件查询</div>
                <div className="content">A与B共同投资的企业</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--CollapseContentSingle icon" aria-hidden="true"></i>
                <div className="title">知识卡片</div>
                <div className="content">"ofo"</div>
              </div>
            </div>
            <div className="ms-Grid-row">
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--ExportMirrored icon" aria-hidden="true"></i>
                <div className="title">路径分析</div>
                <div className="content">ofo和滴滴的关系</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--Financial icon" aria-hidden="true"></i>
                <div className="title">BI统计</div>
                <div className="content">"ofo活跃用户统计"</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--HomeSolid icon" aria-hidden="true"></i>
                <div className="title">实体属性</div>
                <div className="content">"ofo的地址"</div>
              </div>
            </div>
            <div className="ms-Grid-row">
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--Snowflake icon" aria-hidden="true"></i>
                <div className="title">图探索</div>
                <div className="content">"ofo图探索"</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--LineChart icon" aria-hidden="true"></i>
                <div className="title">时序分析</div>
                <div className="content">"ofo发展动态"</div>
              </div>
              <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg4 li">
                <i className="ms-Icon ms-Icon--News icon" aria-hidden="true"></i>
                <div className="title">新闻</div>
                <div className="content">"ofo的新闻"</div>
              </div>
            </div>
          </div>
        </div>
        }
      </div>
    );
  }

  // 获取文献的接口 搜索的文字 data: 分页 排序 筛选
  handleTextSearch = async (data) => {
    let payload
    if (typeof (data) === 'string') {
      payload = {
        text: data
      }
    } else {

      const { keyword } = this.props //
      payload = {
        text: keyword,
        ...data
      }
    }

    const result = await searchSelectedText(payload)
    // console.info("什么时候接口才能通", result)
    const { infobox = {}, document = {} } = result.data
    this.setState({
      showList: true,
      showDocument: document.resCount > 0 ? true : false, //此时显示划词搜索的文档
      document,
      keyword: payload.text,
      skill: infobox.skill,
      list: infobox.data,
      recommodList: infobox.relatedQuestions
    })

  }

}

export default withRouter(Assistant)
